const db = uniCloud.database();
const dbCmd = db.command;
const { defaultChpaters, chapterNameSplitStr } = require('../../config/index.js');
module.exports = async function(options = {}) {
	const { characterId, groupCode, chapters: params_chapters } = options;
	const token = this.getUniIdToken();
	if (!token || !characterId || !groupCode || !params_chapters) {
		throw new Error('非法访问');
	}
	const [groupList, applyList] = await Promise.all([
		db.collection('a-dz-group-list').where({ groupCode }).field({ characterId: true, chapters: true, chapters_custom: true }).get({ getOne: true }),
		db.collection('a-dz-group-apply-list').where({ groupCode, applyStatus: 'AGREE' }).field({ uid: true, chapters: true, chapters_custom: true }).limit(1000).get()
	])
	if (groupList.data.length) {
		const group = groupList.data[0];
		if (group.characterId !== characterId) {
			throw new Error('非法访问');
		}
		const chapters = params_chapters.filter(item => defaultChpaters.find(item2 => item2 === item));
		const chapters_custom = params_chapters.filter(item => !defaultChpaters.find(item2 => item2 === item));
		const group_chapters_custom = group.chapters_custom ? group.chapters_custom : [];
		const elementsNotInGroup = group_chapters_custom.filter(item => !chapters_custom.includes(item));
		const group_chapters_custom_not = elementsNotInGroup.map(item => `${groupCode}${chapterNameSplitStr}${item}`);
		const group_chapters_custom_add = chapters_custom.map(item => `${groupCode}${chapterNameSplitStr}${item}`);
		const promiseDatas = [];

		const uids = applyList.data.map(item => item.uid);
		await Promise.all([
			db.collection('uni-id-users').where({ _id: dbCmd.in(uids) }).update({
				chapters_custom: dbCmd.pullAll(group_chapters_custom_not),
				chapters: dbCmd.addToSet({
					$each: chapters
				})
			}),
			db.collection('uni-id-users').where({ _id: dbCmd.in(uids) }).update({
				chapters_custom: dbCmd.addToSet({
					$each: group_chapters_custom_add
				})
			}),
			db.collection('a-dz-group-list').where({ groupCode }).update({
				chapters,
				chapters_custom
			})
		]);
		return {
			code: 0,
			msg: '修改成功'
		}
	}
}